package com.lyc.shopping_mall.controller;


import com.lyc.shopping_mall.pojo.User;
import com.lyc.shopping_mall.result.Result;
import com.lyc.shopping_mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/my") // 统一添加路径前缀
public class MyController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result<User> login(String username, String userpassword) {
        User user = userService.getUserByUsernameAndPassword(username, userpassword);
        if (user != null) {
            return Result.success(user,"登录成功"); // 成功时调用success方法
        } else {
            return Result.error("用户名或密码错误"); // 失败时调用error方法，传入错误信息
        }
    }

    @RequestMapping("/getAllUsers")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success(users); // 成功时调用success方法
    }


    @PostMapping("/register")
    public Result<User> register(User user) {
        try {
            Integer result = userService.addUser(user);
            if (result != null && result > 0) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败，请稍后重试");
            }
        } catch (DuplicateKeyException e) {
            // 判断是用户名重复还是手机号重复
            if (e.getMessage().contains("user.username")) {
                return Result.error("用户名已存在，请选择其他用户名");
            } else if (e.getMessage().contains("user.userphone")) {
                return Result.error("手机号已存在，请使用其他手机号");
            } else {
                return Result.error("注册失败，数据冲突：" + e.getMessage());
            }
        } catch (Exception e) {
            return Result.error("注册失败，系统异常：" + e.getMessage());
        }
    }





}


